//
//  SN_IAPTool.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/7/3.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_IAPTool.h"


@implementation SN_IAPTool


+(instancetype)ShareTool {
    
    static SN_IAPTool *_tool;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _tool = [[self alloc] init];
    });
    
    return _tool;
}

- (void)getProduct:(NSString *)productId order:(NSString *)orderId delegate:(id)target{
    
    //iap监听
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    self.delegate = target;
    
    if ([SKPaymentQueue canMakePayments]) {
        [Utils showHUD];
        [self getProductInfo:productId];
        self.orderId = orderId;
    } else {
        
        [Utils alertViewWithMessage:@"您尚未开启内购功能，请使用以下方法开启内购：设置>通用>访问限制>开启App内购买项目"];
    }
}

//从Apple查询用户点击购买的产品的信息
- (void)getProductInfo:(NSString *)productIdentifier {
    NSArray *product = [[NSArray alloc] initWithObjects:productIdentifier, nil];
    NSSet *set = [NSSet setWithArray:product];
    SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    request.delegate = self;
    [request start];
    
}

// 查询成功后的回调
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    NSArray *myProduct = response.products;
    if (myProduct.count == 0) {
        [Utils hideHUD];
        [[Utils getCurrentVC] showHint:@"无法获取产品信息，请重试"];
        
        return;
    }
    NSLog(@"%@",myProduct[0]);
    SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//查询失败后的回调
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    
    [Utils hideHUD];
    [[Utils getCurrentVC] showHint:[error localizedDescription]];
    
}

//购买操作后的回调
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
                
                [Utils hideHUD];
                
                //self.receipt = [[NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                self.receipt = [transaction.transactionReceipt base64EncodedStringWithOptions:0];
                
                [self checkReceiptIsValid];//把self.receipt发送到服务器验证是否有效
                [self completeTransaction:transaction];
                [self saveReceipt];
                break;
                
            case SKPaymentTransactionStateFailed://交易失败
                [Utils hideHUD];
                [self failedTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateRestored://已经购买过该商品
                //[self showHint:@"恢复购买成功"];
                [Utils hideHUD];
                [self restoreTransaction:transaction];
                break;
                
            case SKPaymentTransactionStatePurchasing://商品添加进列表
                //[self showHint:@"正在请求付费信息，请稍后"];
                break;
                
            default:
                break;
        }
    }
}


- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    
    if(transaction.error.code == SKErrorPaymentCancelled || transaction.error.code == nil) {
        [Utils hideHUD];
        [[Utils getCurrentVC] showHint:@"用户取消交易"];
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"购买失败，请重试"delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重试", nil];
        alertView.tag = 100;
        [alertView show];
    }
    
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0){
        
        [self saveReceipt];
        
    }else {
        [self checkReceiptIsValid];
    }
}

-(NSString *)base64URLencode:(NSString *)source {
    return [[source stringByReplacingOccurrencesOfString:@"/" withString:@"_"] stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
}

- (void)checkReceiptIsValid{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:[self base64URLencode:self.receipt] forKey:@"receipt"];
    [dict setObject:@"api_szb_iapverify" forKey:@"Method"];
    [dict setObject:self.orderId forKey:@"ordercode"];
    
    [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        [Utils hideHUD];
        NSLog(@"订单详情：%@",jsonObject);
        [self sendAppStoreRequestSucceededWithData];
        
        NSDictionary *imformation = [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID];
        NSMutableDictionary *informationM = [NSMutableDictionary dictionaryWithDictionary:imformation];
        
        [informationM setObject:@"1" forKey:@"isvip"];
        
        [SyUserInfomation personalImformationSaveWtih:informationM];
        
        [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        NSDictionary *re_data = (NSDictionary *)jsonObject;
        
        if (self.delegate && [_delegate respondsToSelector:@selector(orderResult:)]) {
            [self.delegate orderResult:[[re_data objectForKey:@"re_code"] integerValue]];
        }
  
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

//持久化存储用户购买凭证(这里最好还要存储当前日期，用户id等信息，用于区分不同的凭证)
-(void)saveReceipt{
    NSString *fileName = [self getUUIDString];
    NSString *savedPath = [NSString stringWithFormat:@"%@%@.plist", AppStoreInfoLocalFilePath, fileName];
    
    NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:
                        self.receipt,    @"Request_transactionReceipt",
                        USERID,          @"USERID_",
                        self.orderId,    @"ORDERID_",
                        nil];
    
    [dic writeToFile:savedPath atomically:YES];
}

//AppUtils 类的方法，每次调用该方法都生成一个新的UUID
- (NSString *)getUUIDString
{
    CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef strRef = CFUUIDCreateString(kCFAllocatorDefault , uuidRef);
    NSString *uuidString = [(__bridge NSString*)strRef stringByReplacingOccurrencesOfString:@"-" withString:@""];
    CFRelease(strRef);
    CFRelease(uuidRef);
    return uuidString;
}

-(void)sendAppStoreRequestSucceededWithData
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:AppStoreInfoLocalFilePath])
    {
        [fileManager removeItemAtPath:AppStoreInfoLocalFilePath error:nil];
    }
}

@end
